package com.useeinfo.oa.modules.base.dao;

import com.useeinfo.framework.extend.dao.CrudDao;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.QueryUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.base.entity.DataCat;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.*;

/**
 * @Auther: bin.liu
 * @Date: 2018/12/12 15:12
 * @Description: 资料分类管理dao
 */
@Repository("dataCatDao")
public class DataCatDao implements CrudDao<DataCat> {

    private final static Logger logger = LoggerFactory.getLogger(DataCatDao.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Map<String, Object> getSearchCondition(Map<String, String> queryHash){
        Map<String, Object> conditionHash = new HashMap<>();

        conditionHash.put("dc.deleteStatus = ?{paramIndex} ", false);
        if (queryHash == null || queryHash.size() == 0) {
            return conditionHash;
        }
        String searchCode = queryHash.get("searchCode");
        if (!StringUtils.isEmpty(searchCode)) {
            conditionHash.put("(dc.dataCatName like ?{paramIndex}) ", "%" + searchCode + "%");
        }
        String enterpriseId = queryHash.get("enterpriseId");
        if (!StringUtils.isEmpty(enterpriseId)) {
            conditionHash.put("(dc.enterprise.id = ?{paramIndex}) ", StringConverters.ToLong(enterpriseId));
        }
        String dataCatName = queryHash.get("dataCatName");
        if (!StringUtils.isEmpty(dataCatName)) {
            conditionHash.put("(dc.dataCatName like ?{paramIndex}) ", "%" + dataCatName + "%");
        }
        String ids = queryHash.get("ids");
        if (!StringUtils.isEmpty(ids)) {
            String idsSub = ids.substring(ids.indexOf("[") + 1, ids.lastIndexOf("]"));
            String[] idsArr = idsSub.split(",");
            List<Long> idsList = arrStr2LongList(idsArr);
            if (CollectionUtils.isNotEmpty(idsList)) {
                conditionHash.put("(dc.id in (?{paramIndex})) ", idsList);
            }
        }

        return conditionHash;
    }

    /**
     * String[]转List<Long>
     * @param arrStr
     * @return
     */
    public List<Long> arrStr2LongList(String[] arrStr) {
        List<Long> longList = new ArrayList<>();
        for (String str : arrStr) {
            longList.add(StringConverters.ToLong(str.trim()));
        }

        return longList;
    }

    /**
     * 获取总记录数
     */
    @Override
    public Long totalRecord(Map<String, String> queryHash){
        Map<String, Object> conditions = getSearchCondition(queryHash);
        TypedQuery<Long> typedQuery = QueryUtils.getTypedQueryByCondition("select count(dc) from DataCat dc ", conditions, entityManager, Long.class);
        return typedQuery.getSingleResult();
    }

    /**
     * 分页列表
     */
    @Override
    public List<DataCat> findList(QueryParam queryParam){
        String sqlInfo = queryParam.joinJPQL("select dc from DataCat dc ", "order by dc.id desc ");
        Map<String, Object> conditions = getSearchCondition(queryParam.getSqlMap());
        TypedQuery<DataCat> typedQuery = QueryUtils.getTypedQueryByCondition(sqlInfo, conditions, entityManager, DataCat.class);
        return queryParam.findPageList(typedQuery);
    }

    /**
     * id获取记录
     */
    @Override
    public DataCat findModel(Long id){
        return entityManager.find(DataCat.class, id);
    }

    /**
     * 增加记录
     */
    @Override
    public Integer add(DataCat dataCat){
        dataCat.setCreateDate(new Date());
        entityManager.persist(dataCat);
        logger.info("DataCatDaoImpl添加dataCat成功！");
        return 1;
    }

    /**
     * 修改记录
     */
    @Override
    public Integer update(DataCat dataCat){
        dataCat.setUpdateDate(new Date());
        entityManager.merge(dataCat);
        return 1;
    }

    /**
     * 删除记录
     */
    @Override
    public Integer delete(Long id){
        DataCat dataCat = entityManager.find(DataCat.class, id);
        entityManager.remove(dataCat);
        return 1;
    }

    /**
     * 删除记录 - 逻辑删除
     */
    @Override
    public Integer deleteLogic(DataCat dataCat){
        dataCat.setDeleteStatus(true);
        return 1;
    }
}
